#coding=utf-8
'''
# @Name:token_pyjwt.py
# @author:mysouil
# @Description:
# @DATE:2022/9/24 23:44
# @Modified By:
'''
import jwt
from jwt import PyJWTError
from comment.models.user import User
from comment.utils import const
from flask import current_app
from datetime import datetime,timedelta

def generate_token(user_id):
    '''
    根据已经登录之后的用户id，生成token
    :param user_id:用户id
    :return:
    '''

    payload = {
        'id':user_id,
        # exp代表token有效时间，必须是标准时间值
        'exp':datetime.utcnow() + timedelta(seconds=const.JWT_EXPIRY_SECOND)
    }
    
    # 参数1：payload(是一个字典，包括加密的用户id和有效时间) 参数2：key(密钥) 参数3：algorithm(算法名字)
    s = jwt.encode(payload=payload,key=const.SECRET_KEY,algorithm='HS256')
    # 生成token
    return s


def verify_token(token_str):
    '''
    验证token，并且验证成功之后，返回用户id
    :param token_str:
    :return:
    '''
    
    try:
        data = jwt.decode(token_str,key=const.SECRET_KEY,algorithms='HS256')
    except PyJWTError as e:
        current_app.logger.info(e)
        return {'message': 'token is invalid'}
    
    user = User.query.filter(User.id == data['id']).first()
    if user and user.status != 0:
        return {'message': 'user is expired'}
    
    return {'id': user.id}